package com.mvvmhabit.org.custom

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Message
import android.util.AttributeSet
import androidx.viewpager.widget.ViewPager

/**
 * @Date: 2020/11/18 10:19
 * @Author:小妖
 * @Description: 可轮播的ViewPager
 */
open class CustomShufflViewPager(context: Context, attrs: AttributeSet?) :
    ViewPager(context, attrs) {
    var positionIndex = 0

    var pagerLength = 0

    private var isFirstRun = true

    // 创建线程
    private val thread: Thread = Thread(Runnable { pagerHandler.sendEmptyMessageDelayed(0, 3000) })

    @SuppressLint("HandlerLeak")
    private val pagerHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                0 -> {
                    // 移除所有的msg.what为0等消息，保证只有一个循环消息队列再跑
                    this.removeMessages(0)
                    // app的功能逻辑处理
                    // 再次发出msg，循环更新
                    sendEmptyMessageDelayed(0, 3000)
                    if (positionIndex >= pagerLength - 1) {
                        positionIndex = 0
                        currentItem = positionIndex
                    } else {
                        positionIndex = currentItem
                        currentItem = positionIndex + 1
                    }
                }
                1 ->                     // 直接移除，定时器停止
                    this.removeMessages(0)
                else -> {
                }
            }
        }
    }


    fun setPagerLengths(length: Int) {
        pagerLength = length
    }

    fun start() {
        if (isFirstRun) {
            thread.start()
            isFirstRun = false
        }
    }

    fun stop() {
        pagerHandler.sendEmptyMessageDelayed(1, 10)
    }

    fun onResume() {
        pagerHandler.sendEmptyMessageDelayed(0, 3000)
    }
}